package org.example;

import org.example.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Demo03_Insert {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        // 插入操作需不需要定义结果集对象?
        // 不需要,因为插入操作返回的一个整数(受影响的行数)
        try {
            // 1.获取数据库连接
            connection = DBUtil.getConnection();
            // 2.定义SQL
            String sql = "insert into student (sn,name,mail,class_id) value (?,?,?,?) ";
            // 3.定义SQL预处理对象
            statement = connection.prepareStatement(sql);
            // 4. 接收用户参数
            System.out.println("请输入学号:");
            Scanner scanner = new Scanner(System.in);
            String sn = scanner.next();

            System.out.println("请输入姓名:");
            String name = scanner.next();

            System.out.println("请输入邮箱:");
            String mail = scanner.next();

            System.out.println("请输入班级编号:");
            Long classId = Long.valueOf(scanner.next());

            // 5. 用真实数据填充占位符
            statement.setString(1,sn);
            statement.setString(2,name);
            statement.setString(3,mail);
            statement.setLong(4,classId);

            // 6. 执行SQL获取结果
            int row = statement.executeUpdate();
            // 7. 判断结果
            if(row == 1){
                System.out.println("插入成功");
            }else {
                System.out.println("插入失败");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放资源,关闭连接
            DBUtil.close(null,statement,connection);
        }

    }
}
